using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;


namespace Space
{
    /// <summary>
    /// This is a game component that implements IUpdateable.
    /// </summary>
    public class MainMenuComponent : Microsoft.Xna.Framework.DrawableGameComponent
    {
        Screen screen;
        bool lockInput = false;
        Screen nextScreen;

        Dictionary<string, Screen> screens = new Dictionary<string, Screen>();

        float planetRotation = 0;
        float planetRotationSpeed = 0.3f;

        public MainMenuComponent(Game game)
            : base(game)
        {
            // TODO: Construct any child components here
        }

        /// <summary>
        /// Allows the game component to perform any initialization it needs to before starting
        /// to run.  This is where it can query for any required services and load content.
        /// </summary>
        public override void Initialize()
        {
            // TODO: Add your initialization code here
            screens["menu"] = new Screen(Game,
    new Option("Play", "screen", "modes"),
    new Option("Options", "screen", "options"),
    new Option("Exit", "exit"));

            screens["modes"] = new Screen(Game,
                new Option("Campaign", "createGame", "1"),
                new Option("Basic", "createGame", "basic"),
                new Option("Intermediate", "createGame", "intermediate"),
                new Option("Advanced", "createGame", "advanced"),
                new Option("Back", "screen", "menu"));

            screens["options"] = new Screen(Game,
                new Option("Enable horrible music", "toggleOption", "playSong"),
                new Option("Back", "screen", "menu"));

            screen = screens["menu"];


            base.Initialize();
        }

        /// <summary>
        /// Allows the game component to update itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        public override void Update(GameTime gameTime)
        {
            IGameActions gameActions = Game.Services.GetService<IGameActions>();

            if (gameActions.ProgramStage == Stage.Menu)
            {
                IDataInput input = Game.Services.GetService<IDataInput>();
                input.Lock(this);

                float time = (float)gameTime.ElapsedGameTime.TotalSeconds;
                planetRotation += planetRotationSpeed * time;


                screen.Update(time);
                if (!lockInput)
                {
                    if (input.IsKeyClicked(Keys.Down, this) || input.IsButtonPressed(Buttons.LeftThumbstickDown, this))
                    {
                        screen.Navigate(1);
                    }
                    else if (input.IsKeyClicked(Keys.Up, this) || input.IsButtonPressed(Buttons.LeftThumbstickUp, this))
                    {
                        screen.Navigate(-1);
                    }
                    else if (input.IsKeyClicked(Keys.Enter, this) || input.IsButtonPressed(Buttons.A, this))
                    {
                        IData data = Game.Services.GetService<IData>();

                        Option option = screen.SelectedOption;
                        switch (option.command)
                        {
                            case "screen":
                                screen.TransitionFinished += screen_TransitionFinished;
                                screen.Action = ScreenAction.Close;
                                nextScreen = screens[option.argument];
                                lockInput = true;
                                break;
                            case "exit":
                                gameActions.Exit();
                                break;
                            case "createGame":
                                switch (option.argument)
                                {
                                    case "1":
                                        data.CreateLevel(1);
                                        break;
                                    case "basic":
                                        data.CreateGame(numSolar: 2, planetPerSolar: 5, playerPerSolar: 1);
                                        break;
                                    case "intermediate":
                                        data.CreateGame(numSolar: 5, planetPerSolar: 5, playerPerSolar: 1);
                                        break;
                                    case "advanced":
                                        data.CreateGame(numSolar: 2, planetPerSolar: 10, playerPerSolar: 3);
                                        break;
                                }
                                gameActions.ProgramStage = Stage.Game;
                                input.Unlock(this);
                                break;
                            case "toggleOption":
                                option.enabled = !option.enabled;
                                switch (option.argument)
                                {
                                    case "playSong":
                                        gameActions.SetOption("playSong", option.enabled);
                                        break;
                                }
                                break;
                        }
                    }
                }
            }
            base.Update(gameTime);
        }

        void screen_TransitionFinished(Screen sender)
        {
            screen.ResetIndex();
            sender.TransitionFinished -= screen_TransitionFinished;
            screen = nextScreen;
            screen.Action = ScreenAction.Open;
            lockInput = false;
        }

        public override void Draw(GameTime gameTime)
        {
            if (Game.Services.GetService<IGameActions>().ProgramStage == Stage.Menu)
            {
                IGraphics graphics = Game.Services.GetService<IGraphics>();

                graphics.SpriteBatch.Begin();
                graphics.SpriteBatch.Draw(Game.Content.Load<Texture2D>("textures/starsky"), new Rectangle(0, 0, Game.GraphicsDevice.Viewport.Width, Game.GraphicsDevice.Viewport.Height), Color.White);
                graphics.SpriteBatch.DrawString(graphics.Font, "UNTITLED GAME", new Vector2(250, 20), Color.White, 0, Vector2.Zero, 3, SpriteEffects.None, 0);
                graphics.SpriteBatch.End();

                float time = (float)gameTime.ElapsedGameTime.TotalSeconds;

                float fieldOfView = MathHelper.ToRadians(45);
                float distance = 15;
                float aspect = Game.GraphicsDevice.Viewport.AspectRatio;

                Matrix projectionMatrix = Matrix.CreatePerspectiveFieldOfView(fieldOfView, aspect, 0.1f, 50);
                Matrix viewMatrix = Matrix.CreateLookAt(Vector3.Backward * distance, Vector3.Zero, Vector3.Up);

                float scale = 4;

                foreach (ModelMesh mesh in Game.Content.Load<Model>("models/ball").Meshes)
                {
                    foreach (Effect effect in mesh.Effects)
                    {
                        //effect.CurrentTechnique = effect.Techniques["Technique1Logluv"];
                        effect.CurrentTechnique = effect.Techniques["Technique1"];
                        foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                        {
                            pass.Apply();
                            effect.Parameters["World"].SetValue(Matrix.CreateScale(scale) * Matrix.CreateRotationY(planetRotation) * Matrix.CreateTranslation(Vector3.Right * 2 + Vector3.Down * 0.5f));
                            effect.Parameters["Projection"].SetValue(projectionMatrix);
                            effect.Parameters["View"].SetValue(viewMatrix);
                            effect.Parameters["DiffuseColor"].SetValue(Color.White.ToVector3());
                            effect.Parameters["EmissiveColor"].SetValue(Color.Black.ToVector3());
                            effect.Parameters["Light1Direction"].SetValue(Vector3.Left);
                            effect.Parameters["Texture"].SetValue(Game.Content.Load<Texture2D>("textures/earth"));
                        }
                    }
                    mesh.Draw();
                }

                screen.DrawOptions3D(graphics.SpriteBatch, graphics.Font);

                Game.GraphicsDevice.BlendState = BlendState.Opaque;
                Game.GraphicsDevice.DepthStencilState = DepthStencilState.Default;

            }
            base.Draw(gameTime);
        }
    }
}
